package com.tianda.rbac_demo.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianda.rbac_demo.domain.Admin;
import com.tianda.rbac_demo.domain.BaseResult;
import com.tianda.rbac_demo.domain.Menu;
import com.tianda.rbac_demo.domain.MenuVO;
import com.tianda.rbac_demo.mapper.MenuMapper;
import com.tianda.rbac_demo.service.AdminService;
import com.tianda.rbac_demo.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
* @author jinken
* @description 针对表【t_admin】的数据库操作Service实现
* @createDate 2025-09-10 13:31:55
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<MenuVO> getMenuByUsername(String username) {
        //所有菜单数据
        List<MenuVO> menuVOS = baseMapper.selectMenuByAdmin(username);

        //1.过滤出一级菜单数据
        List<MenuVO> parents = menuVOS.stream().filter(menuVO -> menuVO.getPid() == 0).toList();

        //2.循环所有的父菜单
        for (MenuVO parent : parents) {
            //获取父id
            Integer parentId = parent.getId();
            //根据父id过滤出对应的子菜单
            List<MenuVO> children = menuVOS.stream().filter(menuVO -> menuVO.getPid() == parentId).toList();
            //将子菜单集合设置给父
            parent.setChildren(children);
        }


        return parents;
    }

    @Override
    public List<Menu> findAllPermission(String username) {
        return menuMapper.findAllPermission(username);
    }

    @Override
    public BaseResult login(String username, String password) {
        //先根据账号查询数据库账号是否存在
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getAname, username);
        //单行查询
        Admin admin = baseMapper.selectOne(queryWrapper);

        if(Objects.nonNull(admin)){
            //比对密码
            if (admin.getApwd().equals(password)){
                //sa-token登录
                StpUtil.login(username);

                return BaseResult.success();
            }
        }
        return BaseResult.error("账号密码错误");
    }
}




